import { useEffect, useState } from 'react'
import useReactCountdownHook from 'react-countdown-hook';

import useToggle from 'hook/useToggle.jsx';

const initialTime = 60 * 1000; // initial time in milliseconds, defaults to 60000
const initInterval = 1000; // interval to change remaining time amount, defaults to 1000

/**
 * @name 倒计时
 * @description 倒计时hook, 接收三个参数: 初始时间(毫秒), 剩余时间量的间隔, 倒计时结束回调
 */
export default function useCountdown(props) {
    const {
        time = initialTime,
        interval = initInterval,
        callback = () => { }
    } = props || {};
    const [timeLeft, handle] = useReactCountdownHook(time, interval); // handle = { start, pause, resume, reset }
    // 状态开关
    const toggle = useToggle(false);
    // 运行状态: 初始,运行中,暂停中,结束
    const [type, setType] = useState('initial');
    const states = {
        initial: (t) => time,
        running: (t) => t,
        pause: (t) => t,
        end: (t) => 0,
    }
    const state = {
        initial: () => setType('initial'),
        running: () => setType('running'),
        pause: () => setType('pause'),
        end: () => setType('end'),
    }
    // 开始
    const start = () => {
        handle.start();
        toggle.start();
        state.running();
    }
    // 暂停
    const pause = () => {
        handle.pause();
        toggle.stop();
        state.pause();
    }
    // 恢复状态, 继续
    const resume = () => {
        handle.resume();
        toggle.start();
        state.running();
    }
    // 重置
    const reset = () => {
        handle.reset()
        toggle.stop();
        state.initial()
    }

    const running = toggle.loading;
    const left = states[type](timeLeft);
    const count = left / 1000;
    const formatTime = format(count);
    const formatTimeStr = `${formatTime.days}:${formatTime.hours}:${formatTime.mins}:${formatTime.seconds}`;

    useEffect(() => {
        if (timeLeft <= 0 && left <= 0) {
            toggle.stop();
            state.end();
        }
    }, [timeLeft, left])

    useEffect(() => {
        if (!running && left <= 0) {
            callback && callback()
        }
    }, [running, left])

    return {
        timeLeft, // 剩余时间,所属useReactCountdownHook
        left, // 自定义剩余时间(时间戳), 使用这个
        count, // 剩余秒数
        formatTime,
        formatTimeStr,
        running,
        start,
        pause,
        resume,
        reset,
    }
}
const complement = function (number) {
    return number < 10 ? '0' + number : number;
}
const format = function (seconds) {
    let time = { days: '00', hours: '00', mins: '00', seconds: '00', }
    if (!seconds) {
        return time
    }
    time.days = complement(seconds / 60 / 60 / 24 | 0);
    time.hours = complement((seconds / 60 / 60) % 24 | 0);
    time.mins = complement((seconds / 60) % 60 | 0);
    time.seconds = complement(seconds % 60 | 0);
    return time
}